<template>
  <div class="app-container" style="height: 100%">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline style="white-space: nowrap; overflow-x: auto" :class="{ disabled: disableAction }">
      <el-form-item>
        <header-select @selectProject="onSelectProject" style="line-height: normal" />
      </el-form-item>
      <el-form-item prop="planSource">
        <el-select v-model="queryParams.planSource" placeholder="请选择计划来源" clearable style="width: 140px">
          <el-option v-for="item in planSourceList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <template v-if="showBtns.add">
          <el-button size="mini" type="primary" icon="el-icon-plus" @click="openAddItem" v-if="queryParams.projectId">新增计划</el-button>
          <el-popover placement="top" trigger="hover" content="请点击选择左侧项目" v-else>
            <el-button slot="reference" size="mini" icon="el-icon-plus" style="margin-left: 10px">新增计划</el-button>
          </el-popover>
        </template>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="list" size="small" height="calc(100% - 100px)">
      <el-table-column label="计划名称" show-overflow-tooltip min-width="200">
        <span slot-scope="{ row }">
          <el-tag type="info" class="source-tag" size="mini" v-if="row.planSource" :style="{ color: displaySource('color', row.planSource) }" :title="displaySource('label', row.planSource)">
            {{ displaySource('abbr', row.planSource) }}
          </el-tag>
          {{ row.planName }}
        </span>
      </el-table-column>
      <el-table-column label="所属分类" prop="patrolTypeName" show-overflow-tooltip min-width="200" />
      <el-table-column label="巡更点位" min-width="100">
        <el-popover slot-scope="{ row }" placement="right" width="400" trigger="click">
          <span class="pointer" slot="reference">
            共
            <el-link type="primary" style="line-height: 1">{{ row.spotNum }}</el-link>
            个点位
          </span>
          <el-table :data="row.cqPatrolPlanSpotList || []" size="mini">
            <el-table-column label="点位编码" prop="spotCode" show-overflow-tooltip min-width="100" />
            <el-table-column label="点位名称" prop="spotName" show-overflow-tooltip min-width="100" />
            <el-table-column label="负责人" prop="principalNames" show-overflow-tooltip min-width="100" />
          </el-table>
        </el-popover>
      </el-table-column>
      <el-table-column label="重复次数" prop="showCycleName" min-width="100" />
      <el-table-column label="涉及负责人" prop="principalNames" show-overflow-tooltip min-width="100" />
      <el-table-column label="开始时间" prop="planBeginDate" width="150" />
      <el-table-column label="结束时间" prop="planEndDate" width="150" />
      <el-table-column label="下次生成时间" prop="showGenerateDate" width="150" />
      <el-table-column label="状态" align="center" width="80">
        <el-tag slot-scope="{ row }" size="small" :type="row.status ? 'primary' : 'info'">{{ row.status ? '启用' : '禁用' }}</el-tag>
      </el-table-column>
      <el-table-column label="操作" width="240">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="$refs.EditItem.open(row)" v-if="showBtns.edit">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.removeLoading" @click="handleDelete(row)" v-if="showBtns.remove">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-turn-off" :loading="row.isEnableLoading" @click="toggleIsEnable(row)" v-if="row.showDisableBtn">禁用</el-button>
          <el-button size="mini" type="text" icon="el-icon-open" :loading="row.isEnableLoading" @click="toggleIsEnable(row)" v-else-if="row.showEnableBtn">启用</el-button>
          <el-button size="mini" type="text" @click="generateTask(row)" v-if="showBtns.generateTask && row.status == '1' && row.times">生成任务</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <EditItem ref="EditItem" v-model="showEditItem" @ok="getList" />
  </div>
</template>
<script>
// 巡更计划列表
import auth from '@/plugins/auth'
import { getPlan, delPlan, setPlanStatus, generateTask } from '@/api/cq/patrol'
import HeaderSelect from './components/HeaderSelect'
import { planSourceList, cycleTypeList } from './utils/common'
import EditItem from './components/EditPlan'

const planSource2obj = planSourceList.reduce((o, i) => !void (o[i.value] = i) && o, {})
const displaySource = (key, value) => (planSource2obj[value] || {})[key]
const cycleType2label = cycleTypeList.reduce((o, i) => !void (o[i.value] = i.label) && o, {})

export default {
  name: 'PatPlanList',
  components: { HeaderSelect, EditItem },
  data() {
    return {
      displaySource,
      planSourceList,
      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: '',
        planSource: ''
      },
      showEditItem: false
    }
  },
  computed: {
    disableAction() {
      return this.listLoading
    },
    showBtns() {
      // 操作按钮权限
      const permCode = 'cq:patrol:plan'
      const edit = auth.hasPermi(`${permCode}:edit`)
      const add = auth.hasPermi(`${permCode}:add`)
      const remove = auth.hasPermi(`${permCode}:remove`)
      const info = auth.hasPermi(`${permCode}:info`)
      const enable = auth.hasPermi(`${permCode}:enable`)
      const disable = auth.hasPermi(`${permCode}:disable`)
      const generateTask = auth.hasPermi(`${permCode}:generateTask`)
      return { edit, add, remove, info, enable, disable, generateTask }
    }
  },
  methods: {
    onSelectProject(project) {
      const projectId = project?.id || ''
      this.queryParams.projectId = projectId
      if (projectId) this.getList()
    },
    async getList() {
      const { showBtns } = this
      const { projectId } = this.queryParams
      if (!projectId) {
        this.$message('请选择项目')
        return (this.list = [])
      }

      this.listLoading = true
      const res = await getPlan(this.queryParams).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const data = res.rows || []
      data.map(i => {
        i.removeLoading = false
        i.isEnableLoading = false
        i.showDisableBtn = showBtns.disable && i.status
        i.showEnableBtn = showBtns.enable && !i.status
        i.planSource = i.planSource ? i.planSource + '' : ''
        i.spotNum = i.cqPatrolPlanSpotList?.length || 0
        i.showGenerateDate = i.generateDate ? new Date(i.generateDate).Format('yyyy-MM-dd') : ''

        if (i.planType === 'ONCE') {
          i.showCycleName = '1次'
        } else {
          const cycleCount = i.cycleCount === 1 ? '' : i.cycleCount
          i.showCycleName = `每${cycleCount}${cycleType2label[i.cycleType]}${i.times}次`
        }
      })
      this.list = data
      this.total = res.total || 0
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async handleDelete(item) {
      if (item.removeLoading) return
      const res1 = await this.$confirm(`确认删除：${item.planName}？`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await delPlan(item.patPlanId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.list.length > 1 ? this.getList() : this.handleQuery()
    },
    openAddItem() {
      this.$refs.EditItem.open({ projectId: this.queryParams.projectId })
    },
    async toggleIsEnable(item) {
      const isEnable = item.status ? 0 : 1
      const name = isEnable === 1 ? '启用' : '禁用'
      const res1 = await this.$confirm(`确认${name}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = {
        patPlanId: item.patPlanId,
        status: isEnable
      }
      item.isEnableLoading = true
      const res = await setPlanStatus(opt).catch(() => false)
      item.isEnableLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    },
    async generateTask(item) {
      const res1 = await this.$confirm(`确定要生成【${item.planName}】当前周期的巡更任务吗？`, { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { patPlanId: item.patPlanId }
      const res = await generateTask(opt).catch(() => false)
      if (res === false) return

      this.$message.success('已生成巡更任务')
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.source-tag {
  zoom: 0.9;
  margin-right: 2px;
  padding: 0 4px;
}
</style>
